<?php

declare(strict_types=1);

namespace App\Controller;

use App\Model\DataOrderPlaylet;
use App\Model\DataUser;
use App\Model\Playlet;
use App\Model\DataOrder;
use App\Service\HomeService;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\Di\Annotation\Inject;
use App\Common\Response\SystemCode;
use Hyperf\DbConnection\Db;
#[AutoController]
class HomeController  extends BaseController
{
    #[Inject]
    private HomeService $homeService;
    /**
     * 登录
     */
    public function Login(RequestInterface $request, ResponseInterface $response)
    {
        return $this->response(SystemCode::SYSTEM_SUCCESS, '用户不存在或者密码错误');
        $params             = $request->post();
        $userInfo           = $this->homeService->checkUser($params['username'],$params['password']);
        if(empty($userInfo)){
            return $this->response(SystemCode::SYSTEM_ERROR_PASSWORD, '用户不存在或者密码错误');
        }
        $tokenInfo = $this->homeService->generateToken($userInfo->username);
        if(!empty($userInfo->access_token)){
            $this->homeService->delUser($userInfo->access_token);
        }
        $userInfo->ip = $params['ip'] ?? '';
        $userInfo->access_token = $tokenInfo['access_token'];
        $userInfo->save();
        unset($userInfo->password);
        $returnData   = [
            'token'       => $tokenInfo['access_token'],
            'message'     => 'welcome',
            'expire_in'   => $tokenInfo['expire_in'],
            'user'        => $userInfo,
        ];
        $this->homeService->setUser($tokenInfo['access_token'],$returnData);
        return $this->response(SystemCode::SYSTEM_SUCCESS, '登录成功',$returnData);
    }
    /**
     * 首页
     */
    public function Index(RequestInterface $request)
    {
        $userId = 0;
//        if(!empty($request->getHeader('Mema-Token')[0])){
//            $access_token =  $request->getHeader('Mema-Token')[0];
//            $redisInfo = $this->homeService->getUser($access_token);
//            if(empty($redisInfo)){
//                return $this->response(SystemCode::SYSTEM_TOKEN_EXPIRE, '用户不存在');
//            }
//            $userInfo =  DataUser::query()->where('access_token',$access_token)->select('id')->first();
//            if(empty($userInfo)){
//                return $this->response(SystemCode::SYSTEM_TOKEN_EXPIRE, '用户不存在 获取token过期');
//            }
//            $userId = $userInfo->id;
//        }

        $data = $this->homeService->index($userId);

        return $this->response(SystemCode::SYSTEM_SUCCESS, '请求成功', $data);

    }
    /**
     * 标签
     */
    public function Tag(RequestInterface $request)
    {
        $data = $this->homeService->tag();

        return $this->response(SystemCode::SYSTEM_SUCCESS, '请求成功', $data);

    }
    /**
     * 列表
     */
    public function List(RequestInterface $request)
    {
        $userId = 0;
//        if(!empty($request->getHeader('Mema-Token')[0])){
//            $access_token =  $request->getHeader('Mema-Token')[0];
//            $redisInfo = $this->homeService->getUser($access_token);
//            if(empty($redisInfo)){
//                return $this->response(SystemCode::SYSTEM_TOKEN_EXPIRE, '用户不存在');
//            }
//            $userInfo =  DataUser::query()->where('access_token',$access_token)->select('id')->first();
//            if(empty($userInfo)){
//                return $this->response(SystemCode::SYSTEM_TOKEN_EXPIRE, '用户不存在 获取token过期');
//            }
//            $userId = $userInfo->id;
//        }

        $data = $this->homeService->list($request->post(),$userId);

        return $this->response(SystemCode::SYSTEM_SUCCESS, '请求成功', $data);

    }
    /**
     * 短剧详情
     */
    public function Episodes($id,RequestInterface $request){

        if(!empty($id)) {
            $playletInfo = Playlet::query()->select('id', 'name', 'status')->where('id', $id)->first();
            if (empty($playletInfo)) {
                return $this->response(SystemCode::SYSTEM_ERROR, '短剧不存在');
            }
            $data = $this->homeService->episodes($id);
            return $this->response(SystemCode::SYSTEM_SUCCESS, '请求成功', $data);
        }
    }
    /**
     * 下单
     */
    public function Order(RequestInterface $request){

        try {
            Db::beginTransaction();
//            if(empty($request->getHeader('Mema-Token')[0])){
//                return $this->response(SystemCode::SYSTEM_TOKEN_EXPIRE, 'token 不存在');
//            }
//
//            $access_token =  $request->getHeader('Mema-Token')[0];
//            $redisInfo = $this->homeService->getUser($access_token);
//            if(empty($redisInfo)){
//                return $this->response(SystemCode::SYSTEM_TOKEN_EXPIRE, '用户不存在');
//            }
//            $userInfo =  DataUser::query()->where('access_token',$access_token)->select('id')->first();
//            if(empty($userInfo)){
//                return $this->response(SystemCode::SYSTEM_TOKEN_EXPIRE, '用户不存在 获取token过期');
//            }
            $params             = $request->post();
            $phone              = $params['phone'];
            $playletIds         = $params['playletIds'];

            $playletInfo = Playlet::query()->whereIn('id',$playletIds)->select(['id','name'])->get()->toArray();
            if(empty($playletInfo)){
                return $this->response(SystemCode::SYSTEM_ERROR, '短剧不存在');
            }
//            $haveOrder = DataOrderPlaylet::query()->whereIn('playlet_id',$playletIds)->where(['data_user_id' => $userInfo->id])->get();
//
//            if($haveOrder->isNotEmpty()){
//                $errorMeg = [];
//                foreach ($haveOrder as $order){
//                    $errorMeg[] = '《'.$order->playlet->name.'》短剧 已经购买过';
//                }
//                return $this->response(SystemCode::SYSTEM_ERROR, '短剧存在已购买的短剧',$errorMeg);
//            }
            //先创建订单
            $dataOrder = new DataOrder();
            $dataOrder->data_user_id = 0;//$userInfo->id;
            $dataOrder->phone = $phone;
            if($dataOrder->save()){
                $playlet_name = [];
                foreach ($playletInfo as $playlet){
                    DataOrderPlaylet::create([
                        'data_user_id' => 0,//$userInfo->id,
                        'data_order_id' => $dataOrder->id,
                        'playlet_id' => $playlet['id'],
                    ]);
                    $playlet_name[] = $playlet['name'];
                }
                Db::commit();
                return $this->response(SystemCode::SYSTEM_SUCCESS, '提交订单成功',[
                    'id' => $dataOrder->id,
                    'phone' => $dataOrder->phone,
                    'created_at' => $dataOrder->created_at,
                    'name' => implode(',',$playlet_name),
                ]);
            }else{
                Db::rollBack();
                return $this->response(SystemCode::SYSTEM_ERROR, '提交订单失败');
            }
        }catch (\Exception $e){
            Db::rollBack();
            return $this->response(SystemCode::SYSTEM_ERROR, $e->getMessage());
        }
    }


    public function orderList(RequestInterface $request){

        return $this->response(SystemCode::SYSTEM_SUCCESS, '没有订单');
        if(empty($request->getHeader('Mema-Token')[0])){
            return $this->response(SystemCode::SYSTEM_TOKEN_EXPIRE, 'token 不存在');
        }

        $access_token =  $request->getHeader('Mema-Token')[0];
        $redisInfo = $this->homeService->getUser($access_token);
        if(empty($redisInfo)){
            return $this->response(SystemCode::SYSTEM_TOKEN_EXPIRE, '用户不存在');
        }
        $userInfo =  DataUser::query()->where('access_token',$access_token)->select('id')->first();
        if(empty($userInfo)){
            return $this->response(SystemCode::SYSTEM_TOKEN_EXPIRE, '用户不存在 获取token过期');
        }
        $dataOrderInfo = DataOrder::query()->select(['id','phone','status','created_at'])->where(['data_user_id' => $userInfo->id])->orderBy('updated_at','desc')->get();
        if(!empty($dataOrderInfo)) {
            foreach ($dataOrderInfo as &$value){

                $playletIds = DataOrderPlaylet::query()->where(['data_order_id' => $value->id,'data_user_id' => $userInfo->id])->pluck('playlet_id');
                $value->playlet_name = '';
                if(!empty($playletIds)){
                   $playletNameData = Playlet::query()->whereIn('id',$playletIds)->pluck('name')->toArray();
                   $value->playlet_name = implode(',',$playletNameData);
                }
            }
            return $this->response(SystemCode::SYSTEM_SUCCESS, '提交订单成功',$dataOrderInfo);
        }else{
            return $this->response(SystemCode::SYSTEM_SUCCESS, '没有订单');
        }
    }
}